package cn.lmxdev.ptms.service.impl;

import cn.lmxdev.ptms.bean.exception.BizException;
import cn.lmxdev.ptms.bean.table.TUserInfo;
import cn.lmxdev.ptms.dao.IUserInfoDao;
import cn.lmxdev.ptms.service.IUserInfoServlet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserInfoServletImpl implements IUserInfoServlet {
    private final IUserInfoDao userInfoDao;

    @Autowired
    public UserInfoServletImpl(
            IUserInfoDao userInfoDao
    ) {
        this.userInfoDao = userInfoDao;
    }

    @Override
    @Transactional
    public TUserInfo get(Long id) {
        return this.userInfoDao.find(id);
    }

    @Override
    @Transactional
    public long add(TUserInfo userInfo) {
        // 插入数据
        if (!this.userInfoDao.insert(userInfo))
            throw new BizException("操作失败");

        // 返回ID
        return userInfo.getId();
    }

    @Override
    @Transactional
    public void remove(Long id) {
        // 删除失败
        if (!this.userInfoDao.delete(id))
            throw new BizException("操作失败");
    }

    @Override
    @Transactional
    public void edit(TUserInfo userInfo) {
        // 查询旧数据
        TUserInfo oldUserInfo = this.userInfoDao.find(userInfo.getId());

        // 更新属性
        oldUserInfo.setName(userInfo.getName())
                .setGender(userInfo.getGender())
                .setPhone(userInfo.getPhone())
                .setEmail(userInfo.getEmail())
                .setQq(userInfo.getQq())
                .setDingding(userInfo.getDingding());

        // 保存数据
        if (!this.userInfoDao.update(oldUserInfo))
            throw new BizException("操作失败");
    }

    @Override
    @Transactional
    public long count(TUserInfo userInfo) {
        return this.userInfoDao.count(userInfo);
    }

    @Override
    @Transactional
    public List<TUserInfo> list(Long limit, Long page, TUserInfo userInfo) {
        return this.userInfoDao.select(page != null ? (page - 1) * limit : null, limit, userInfo);
    }
}
